
import java.awt.Point;
import java.util.*;

/**
 * The Model part of the application. Does all the work behind the {@link View}.<p>
 * Contains the main driver method.
 * 
 * @author Alex Mackay
 */
public class Model {
	
	public static void main(String[] args) throws java.rmi.RemoteException{
		
		int port;
		
		Model m = new Model();
		
		if(args.length == 0) {
			
		} else if(args.length == 1) {
			try {
				port = Integer.valueOf(args[0]);
				
			} catch(NumberFormatException nfe){
				return;
			}
			
			m.startServer(port);
			
		} else if(args.length == 2){
			
			String url = args[0];
			
			try{
				port = Integer.valueOf(args[1]);
				
			} catch(NumberFormatException nfe){
				return;
			}
			
			m.connectToRemoteServer(url, port);
			
		} else {
			System.out.println("usage:");
			System.out.println("java CardsServer <> - creates a master on port 1099");
			System.out.println("java CardsServer <port> - creates a master on specified port");
			System.out.println("java CardsServer <masterServer Name><port> - creates a slave connecting to master on port");
		}
	}
	
	
	private View view;
	
	private CardsServer cs;
	private PlayerModel localplayer;
	
	
	
	/**
	 * Constructs a <code>Model</code> object.
	 */
	public Model() {
		Dbg.logln("Model constructor");
		this.setView(new View(this));
		startServer(1099);
	}
	
	
	/**
	Starts a local server.
	*/
	public void startServer(int port) {
		Dbg.logln("startServer");
		try {
			cs = new CardsServer(port);
			this.setPlayer(new PlayerModel());
		} catch (java.rmi.RemoteException e) {
			System.err.println("couldnt instantiate CardsServer for some reason");
			e.printStackTrace();
		}
	}
	
	
	public void setPlayer(PlayerModel pm) {
		Dbg.logln("setPlayer");
		this.localplayer = pm;
		cs.addPlayer(localplayer);
		view.setPlayer(localplayer);
		
	}
	
	
	/**
	Connects the local program to the local server.
	*/
	public void connectToLocalServer() {
		Dbg.logln("connectToLocalServer");
	}
	
	/**
	Connects the local program to a remote server.
	*/
	public boolean connectToRemoteServer(String server, int port) {
		Dbg.logln("connectToRemoteServer");
		try{
			cs.slaveMode(server, port);
			return true;
		}
		catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * Sets the {@link View} object for this <code>Model</code>.
	 * 
	 * @param view The <code>View</view> object to set.
	 */
	public void setView(View view) {
		Dbg.logln("setView");
		this.view = view;
	}	
	
	public boolean updateView() {
		Dbg.logln("updateView");
		view.repaint();
		localplayer.alert();
		return true;
	}
	
	public void setSnap(boolean s) {
		cs.setSnap(s);
	}
	
	
}
